package com.azxcrm.project.system.wap.controller;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.azxcrm.common.utils.DateUtils;
import com.azxcrm.common.utils.security.ShiroUtils;
import com.azxcrm.framework.aspectj.lang.annotation.Log;
import com.azxcrm.framework.web.domain.Message;
import com.azxcrm.project.monitor.workflow.domain.WorkFlowApply;
import com.azxcrm.project.monitor.workflow.service.WorkFlowApplyService;
import com.azxcrm.project.system.basic.domain.CustomerClueCommunication;
import com.azxcrm.project.system.basic.domain.OrderDispatch;
import com.azxcrm.project.system.basic.service.ICustomerClueCommunicationService;
import com.azxcrm.project.system.basic.service.IOrderDispatchService;
import com.azxcrm.project.system.customer.domain.CustomerAttendance;
import com.azxcrm.project.system.customer.domain.CustomerClue;
import com.azxcrm.project.system.customer.service.ICustomerAttendanceService;
import com.azxcrm.project.system.customer.service.ICustomerClueService;
import com.azxcrm.project.system.order.domain.Order;
import com.azxcrm.project.system.order.domain.OrderDeal;
import com.azxcrm.project.system.order.domain.OrderVisitRecord;
import com.azxcrm.project.system.order.service.IOrderDealService;
import com.azxcrm.project.system.order.service.IOrderService;
import com.azxcrm.project.system.order.service.IOrderVisitRecordService;
import com.azxcrm.project.system.user.domain.User;
import com.azxcrm.project.system.user.service.IUserService;


/**
 * 
 * 订单模块
 * @author Administrator
 * @date 2018-09-28
 * 
 */
@Controller
@RequestMapping("/wap/order")
public class WapOrderController {
	
	private String prefix = "wap/order";
	
	private String index = "wap/relatedme";
	
	@Autowired
	private IOrderService orderService;
	
	@Autowired
	private IOrderDispatchService orderDispatchService;
	
	@Autowired
	private IOrderDealService orderDealService;
	
	@Autowired
	private WorkFlowApplyService workFlowApplyService;
	
	@Autowired
	private ICustomerClueService customerClueService;
	
	/**
	 * 参课信息
	 */
	@Autowired
	private ICustomerAttendanceService customerAttendanceService;
	
	/**
	 * 客服沟通记录
	 */
	@Autowired
	private ICustomerClueCommunicationService customerClueCommunicationService;
	
	/**
	 * 用户信息
	 */
	@Autowired
	private IUserService userService;
	
	/**
	 * 回访记录表
	 */
	@Autowired
	private IOrderVisitRecordService orderVisitRecordService;
	
	/**
	 * 业务员角色
	 */
	@Value("${crm.role.salesman}")
	private String salesman;
	
	/**
	 * 我的订单-查询跟进中，待审核，已结单，已退单的订单列表详情
	 * @return
	 * @throws ParseException 
	 */
	@Log(title = "Wap我的订单", action = "查询跟进中，待审核，已结单，已退单的订单列表详情")
	@RequestMapping("/followOrder")
	public String followOrder(Order order,OrderDispatch orderDispatch, OrderDeal orderDeal,
				  Model model) throws ParseException{		
		order.setSalesUserId(ShiroUtils.getUserId().intValue());
		orderDispatch.setOrder(order);
		//查询跟进中列表信息
		List<OrderDispatch> dispatchList = orderDispatchService.wapOrderDispatchList(orderDispatch);
		List<OrderDispatch> orderDispatchList = new ArrayList<OrderDispatch>();
   		for (OrderDispatch od : dispatchList) {
   			Long dateNum = DateUtils.getDaySub(DateUtils.getDate(), od.getProtectTime());
   			od.setDateNum(dateNum);
   			orderDispatchList.add(od);
   			if(dateNum<0) {
   				order.setOrderStatus(0);
   			}
   		}
		model.addAttribute("orderDispatchList", orderDispatchList);
		//查询待审核列表信息
		List<Order> auditOrderList = orderService.selectOrderList(order);
		model.addAttribute("auditOrderList", auditOrderList);
		//查询已结单和已退单列表信息
		orderDeal.setOrder(order);
		List<OrderDeal> orderDealList = orderDealService.OrderDealList(orderDeal);
		List<OrderDeal> oDealList = new ArrayList<>();
		for (OrderDeal oDeal : orderDealList) {
			String dealTime = oDeal.getDealTime();
			oDeal.setDealTime(dealTime.substring(0,19));
			oDealList.add(oDeal);
		}
		model.addAttribute("orderDealList", oDealList);
 		return prefix + "/followOrder";
	}
	
	/**
	 * 我的订单-跟进中-待跟进订单保护期内订单详情
	 * @return
	 */
	@Log(title = "Wap我的订单", action = "跟进中-待跟进订单保护期内订单详情")
	@GetMapping("/wapOrderDetail")
	public String wapOrderDetails(@RequestParam("orderId")Integer orderId,Model model) throws ParseException{	
		// 查询订单信息
		Order order= orderService.selectOrderById(orderId);
		model.addAttribute("order", order);

		// 查询客户线索信息
		CustomerClue customerClue = customerClueService.selectCustomerClueById(order.getClueId());
		model.addAttribute("customerClue", customerClue);
		
		// 参课记录
		List<CustomerAttendance> customerAttendance = customerAttendanceService
				.selectCustomerAttendanceByCellphone(customerClue.getCustomerCellphone());
		model.addAttribute("customerAttendanceList", customerAttendance);
		
		//获取客服电话
		User user = userService.selectUserById(order.getServiceUserId().longValue());
		model.addAttribute("user", user);		
		
		//查询剩余保有时间
		OrderDispatch orderDispatch = orderDispatchService.selectOrderDispatchById(order.getOrderId());
		model.addAttribute("orderDispatch", orderDispatch);
		long protectDay = DateUtils.getDaySub(DateUtils.getDate(), orderDispatch.getProtectTime());
		model.addAttribute("protectDay", protectDay);
		
		// 查询客服沟通记录
		CustomerClueCommunication clueCommunication = customerClueCommunicationService
				.selectCustomerClueCommunicationByClueId(order.getClueId());
		model.addAttribute("clueCommunication", clueCommunication);
		
		//查询跟单记录
		List<OrderVisitRecord> orderVisitRecords= orderVisitRecordService.selectOrderVisitRecordByOrderId(orderId);
		model.addAttribute("orderVisitRecords", orderVisitRecords);
		return prefix + "/orderDetail";
	}
	
	/**
	 * 我的订单-跟进中-未成单原因
	 * @return
	 */
	@Log(title = "Wap我的订单", action = "跟进中-未成单原因页面")
	@RequestMapping("/orderReason")
	public String orderReason(){
		return prefix + "/orderReason";
	}
	
	/**
	 * 我发起的审核-查询成单，退单列表和被驳回信息
	 * @return
	 */
	@Log(title = "Wap我发起的审核", action = "查询成单和退单列表信息和被驳回信息")
	@RequestMapping("/askOrder")
	public String auditOrder(WorkFlowApply workFlowApply, Model model){
		workFlowApply.setUserId(ShiroUtils.getUserId().intValue());
		List<WorkFlowApply> workFlowApplyList = workFlowApplyService.selectWorkFlowApplyList(workFlowApply);
		model.addAttribute("workFlowApplyList", workFlowApplyList);
		return prefix + "/askOrder";
	}
	
	/**
	 * 我发起的审核-发起待审批-退单详情
	 * @return
	 */
	@Log(title = "Wap我发起的审核", action = "发起待审批-退单详情")
	@RequestMapping("/askForOrder")
	public String askForOrder(Integer applyId, Model model){
		WorkFlowApply workFlowApply = workFlowApplyService.selectWorkFlowApplyByApplyId(applyId);
		model.addAttribute("workFlowApply", workFlowApply);
		Order order = orderService.selectOrderById(workFlowApply.getOrderId());
		model.addAttribute("order", order);
		return prefix + "/askForOrder";
	}
	
	/**
	 * 我发起的审核-发起待审批-成单详情
	 * @return
	 */
	@Log(title = "Wap我发起的审核", action = "发起待审批-成单详情")
	@RequestMapping("/detailsOrder")
	public String detailsOrder(Integer applyId, Model model){
		WorkFlowApply workFlowApply = workFlowApplyService.selectWorkFlowApplyByApplyId(applyId);
		model.addAttribute("workFlowApply", workFlowApply);
		Order order = orderService.selectOrderById(workFlowApply.getOrderId());
		model.addAttribute("order", order);
		return prefix + "/detailsOrder";
	}
	
	/**
	 * 我的订单-待审核-待审核订单详情
	 * @return
	 */
	@Log(title = "Wap我的订单", action = "待审核-待审核订单详情")
	@RequestMapping("/waitAuditOrder")
	public String waitAuditOrder(Integer orderId, Model model){
		Order order = orderService.selectOrderById(orderId);
		model.addAttribute("order", order);
		return prefix + "/waitAuditOrder";
	}
	
	/**
	 * 我的订单-待审核-待审核订单详情-放弃订单
	 * @return
	 */
	@Log(title = "Wap我的订单", action = "待审核-待审核订单详情-放弃订单")
	@RequestMapping("/giveUpOrder")
	@ResponseBody
	public Message giveUpOrder(Integer orderId, OrderDeal orderDeal, 
				OrderDispatch orderDispatch, Model model){
		Order order = orderService.selectOrderById(orderId);
		order.setAuditStatus(3);
		int count = 0;
		//线上订单修改为待分配订单
		if(order.getOrderType()==0){
			order =new Order(orderId, 0, 0, 0);
			count = orderService.updateOrder(order);
		//线下订单修改为流单
		}else if(order.getOrderType()==1){
			order =new Order(orderId, 7, 0, 0);
			count = orderService.updateOrder(order);
		}
		if(count > 0){
			return Message.ok();
		}
		return Message.error();
	}
	
	/**
	 * 我的订单-待审核-待审核订单详情-修改订单审核
	 * @return
	 */
	@Log(title = "Wap我的订单", action = "待审核-待审核订单详情-修改订单审核")
	@RequestMapping("/saveOrder")
	public String saveOrder(Integer orderId,Order order,Model model){
		order.setOrderId(orderId);
		int count = orderService.updateOrder(order);
		if(count > 0){
			Message.ok("修改审核订单成功,正在加载数据......");
		}
		return prefix + "/followOrder";
	}
	
	/**
	 * 我的订单-已结单详情
	 * @return
	 */
	@Log(title = "Wap我的订单", action = "已结单详情")
	@RequestMapping("/finishOrder")
	public String finishOrder(Integer orderId, Model model){
		OrderDeal orderDeal = orderDealService.selectOrderDealById(orderId);
		String dealTime = orderDeal.getDealTime();
		orderDeal.setDealTime(dealTime.substring(0,19));
		model.addAttribute("orderDeal", orderDeal);
		return prefix + "/finishOrder";
	}
	
	/**
	 * 我的订单-已结单详情-发起退单详情页
	 * @return
	 */
	@Log(title = "Wap我的订单", action = "已结单详情-发起退单详情页")
	@RequestMapping("/refundOrder")
	public String refundOrder(Integer orderId, Model model){
		model.addAttribute("orderId", orderId);
		return prefix + "/refundOrder";
	}
	
	/**
	 * 我的订单-已结单详情-发起退单逻辑
	 * @param order
	 * @return
	 */
	@Log(title = "Wap我的订单", action = "已结单详情-发起退单逻辑")
	@RequestMapping("/refund")
	@ResponseBody
	public Object refund(Order order){
		int ret = orderService.wapFlowOrderDeal(order);
		JSONObject object = new JSONObject();
		object.put("msg", ret);
		return object;
	}
	
	/**
	 * 我的订单-退单详情
	 * @return
	 */
	@Log(title = "Wap我的订单", action = "退单详情")
	@RequestMapping("/cancelOrder")
	public String cancelOrder(Integer orderId, Model model){
		OrderDeal orderDeal = orderDealService.selectOrderDealById(orderId);
		String dealTime = orderDeal.getDealTime();
		orderDeal.setDealTime(dealTime.substring(0,19));
		model.addAttribute("orderDeal", orderDeal);
		return prefix + "/cancelOrder";
	}
	
	/**
	 * 参课记录-查询客户参课记录列表
	 * @param customerAttendance
	 * @param model
	 * @return
	 */
	@Log(title = "Wap参课记录", action = "查询客户参课记录列表")
	@RequestMapping("/myCustomerAttendance")
	public String myCustomer(CustomerAttendance customerAttendance, Model model){
		customerAttendance.setSalesUserId(ShiroUtils.getUserId().intValue());
		List<CustomerAttendance> list = customerAttendanceService.selectCustomerAttendanceList(customerAttendance);
		model.addAttribute("list", list);
		return index + "/myCustomerAttendance";
	}
	
	/**
	 * 参课记录-查询客户参课记录-查询参课信息详情
	 * @param attendId
	 * @param model
	 * @return
	 */
	@Log(title = "Wap参课记录", action = "查询客户参课记录-查询参课信息详情")
	@RequestMapping("/recordAttendance")
	public String visitRecord(Integer attendId, Model model){
		CustomerAttendance customerAttendance = customerAttendanceService.selectCustomerAttendanceById(attendId);
		model.addAttribute("customerAttendance", customerAttendance);
		return index + "/recordAttendance";
	}
	
	/**
	 * 参课记录-查询客户参课记录-添加参课信息详情页
	 * @param model
	 * @return
	 */
	@Log(title = "Wap参课记录", action = "查询客户参课记录-添加参课信息详情页")
	@RequestMapping("/customerAttendance")
	public String addCustomer(Model model){
		User user = userService.selectUserById(ShiroUtils.getUserId());
		model.addAttribute("user", user);
		return index + "/addCustomerAttendance";
	}
	
	/**
	 * 参课记录-查询客户参课记录-添加参课信息详情页-添加参课信息逻辑
	 * @param customerAttendance
	 * @return
	 */
	@Log(title = "Wap参课记录", action = "查询客户参课记录-添加参课信息详情页-添加参课信息逻辑")
	@RequestMapping("/addCustomerAttendance")
	@ResponseBody
	public Message add(CustomerAttendance customerAttendance){
		customerAttendance.setSalesUserId(ShiroUtils.getUserId().intValue());
		customerAttendance.setCreateBy(ShiroUtils.getLoginName());
		if(customerAttendanceService.insertCustomerAttendance(customerAttendance)>0){
			return Message.ok();
		}
		return Message.error();
	}
	
	
	@Log(title = "Wap验证原始密码", action = "个人信息-验证原始密码")
    @RequestMapping("/checkPassword")
    @ResponseBody
    public boolean checkPassword(String password)
    {
        User user = ShiroUtils.getUser();
        String encrypt = new Md5Hash(user.getLoginName() + password + user.getSalt()).toHex().toString();
        if (user.getPassword().equals(encrypt))
        {
            return true;
        }
        return false;
    }
	

	@Log(title = "Wap修改密码", action = "个人信息-重置密码")
	@RequestMapping("/changePassword")
    public String changePassword(Model model)
    {
        User user = userService.selectUserById(ShiroUtils.getUserId());
        model.addAttribute("user", user);
        return prefix + "/changePassword";
    }
	
    @Log(title = "Wap修改密码", action = "个人信息-重置密码")
    @PostMapping("/resetPassword")
    @ResponseBody
    public Message resetPassword(User user)
    {
    	int rows = userService.resetUserPwd(user);
        if (rows > 0)
        {
            ShiroUtils.setUser(userService.selectUserById(user.getUserId()));
            return Message.ok();
        }
        return Message.error();
}
}
